import Phaser from 'phaser'
import { GroupBar } from '../ui/GroupBar.js';
import { NumberUtils } from '../utils/NumberUtils.js';
import { SoundUtils } from '../utils/SoundUtils.js';

// 星际对比跳：大小比较
export class ModeCScene extends Phaser.Scene {
  rangeMode= 'yi'
  totalRounds= 10
  currentRound= 0
  score= 0

  numberA!: number
  numberB!: number
  questionType: 'bigger' | 'smaller' = 'bigger' // 随机问题类型

  titleText!: Phaser.GameObjects.Text
  promptText!: Phaser.GameObjects.Text
  numberAText!: Phaser.GameObjects.Text
  numberBText!: Phaser.GameObjects.Text
  buttonA!: Phaser.GameObjects.Text
  buttonB!: Phaser.GameObjects.Text
  feedbackText!: Phaser.GameObjects.Text
  hintText!: Phaser.GameObjects.Text
  hudText!: Phaser.GameObjects.Text
  groupBar!: any // 暴露给 MainScene 使用

  constructor() {
    super('ModeCScene')
  }

  init(data) {
    this.rangeMode = data.rangeMode || 'yi'
    this.totalRounds = data.totalRounds || 10
  }

  create() {
    console.log('ModeCScene created with range:', this.rangeMode)

    // 初始化音效
    SoundUtils.init()

    // 监听场景关闭事件，清理延时调用
    this.events.once('shutdown', () => {
      this.time.removeAllEvents()
    })

    // 监听变化
    this.events.on('rangeChanged', (newRange) => {
      this.rangeMode = newRange
      this.resetRounds()
    })
    this.events.on('roundsChanged', (val) => {
      this.totalRounds = val
      this.resetRounds()
    })

    this.createUI()
    this.resetRounds()
  }

  createUI() {
    // 添加场景内导航
    this.createInGameMenu()

    // 标题
    this.titleText = this.add.text(160, 100, '星际对比跳：大小比较', { fontSize: '28px', color: '#22D3EE' })

    // HUD
    this.hudText = this.add.text(1120, 60, '', { fontSize: '18px', color: '#9CA3AF' }).setOrigin(1,0)

    // 题目提示 - 增大字体确保可见
    this.promptText = this.add.text(640, 140, '哪个数字更大？', {
      fontSize: '36px', color: '#FDE047', fontFamily: 'Arial, sans-serif',
      align: 'center', stroke: '#000000', strokeThickness: 2
    }).setOrigin(0.5).setDepth(1000)

    // 数字A显示区域
    const containerA = this.add.container(360, 280)
    const bgA = this.add.rectangle(0, 0, 360, 120, 0x2D3748, 0.85)
    containerA.add(bgA)
    const labelA = this.add.text(-150, -40, 'A', { fontSize: '24px', color: '#FDE047' }).setOrigin(0.5)
    containerA.add(labelA)
    this.numberAText = this.add.text(0, 10, '', { fontSize: '44px', color: '#D9E8FF', align: 'center' }).setOrigin(0.5)
    containerA.add(this.numberAText)

    // 数字B显示区域
    const containerB = this.add.container(920, 280)
    const bgB = this.add.rectangle(0, 0, 360, 120, 0x2D3748, 0.85)
    containerB.add(bgB)
    const labelB = this.add.text(-150, -40, 'B', { fontSize: '24px', color: '#FDE047' }).setOrigin(0.5)
    containerB.add(labelB)
    this.numberBText = this.add.text(0, 10, '', { fontSize: '44px', color: '#D9E8FF', align: 'center' }).setOrigin(0.5)
    containerB.add(this.numberBText)

    // 选择按钮 - 只显示A和B，不显示"更大"等误导性文字
    this.buttonA = this.add.text(360, 440, 'A', { fontSize: '32px', color: '#D9E8FF', backgroundColor: '#2D3748', padding: { x: 50, y: 20 } }).setOrigin(0.5).setInteractive({ useHandCursor: true })
    this.buttonB = this.add.text(920, 440, 'B', { fontSize: '32px', color: '#D9E8FF', backgroundColor: '#2D3748', padding: { x: 50, y: 20 } }).setOrigin(0.5).setInteractive({ useHandCursor: true })

    // 按钮交互
    this.setupButtonInteractions()

    // 反馈文本
    this.feedbackText = this.add.text(640, 520, '', { fontSize: '20px', color: '#FDE047', align: 'center' }).setOrigin(0.5)

    // 提示文本
    this.hintText = this.add.text(640, 600, '提示：比较大数时，先看最高数级（亿级 > 万级 > 千级）', { fontSize: '16px', color: '#9CA3AF' }).setOrigin(0.5)

    // 装饰
    this.createNebulaBackground()
    this.createDecorations()

    // 小组竞赛条 — 仅允许🌍
    this.groupBar = new GroupBar(this, 20, 620, 1240, 'earth')
    this.add.existing(this.groupBar)

    // 添加重置成绩按钮
    this.createResetButton()

    // 键盘控制现在由 MainScene 全局处理
  }

  setupButtonInteractions() {
    // 按钮A
    this.buttonA.on('pointerover', () => {
      this.buttonA.setStyle({ backgroundColor: '#4A5568' })
    })
    this.buttonA.on('pointerout', () => {
      this.buttonA.setStyle({ backgroundColor: '#2D3748' })
    })
    this.buttonA.on('pointerdown', () => {
      this.onChoiceSelected('A')
    })

    // 按钮B
    this.buttonB.on('pointerover', () => {
      this.buttonB.setStyle({ backgroundColor: '#4A5568' })
    })
    this.buttonB.on('pointerout', () => {
      this.buttonB.setStyle({ backgroundColor: '#2D3748' })
    })
    this.buttonB.on('pointerdown', () => {
      this.onChoiceSelected('B')
    })
  }

  createDecorations() {
    // 添加星星装饰（弱化，不干扰前景）
    for (let i = 0; i < 25; i++) {
      const x = Math.random() * 1280
      const y = Math.random() * 720
      const star = this.add.circle(x, y, Math.random() * 2 + 1, 0x6366F1, 0.25)
      star.setDepth(-5)
      this.tweens.add({ targets, alpha: 0.12, duration: 1000 + Math.random() * 3000, yoyo, repeat: -1 })
    }

    // 对比天平装饰（轻度摆动）
    const scale = this.add.rectangle(640, 350, 200, 4, 0x6B7280).setDepth(-4)
    const leftPan = this.add.rectangle(580, 340, 40, 20, 0x4B5563).setDepth(-4)
    const rightPan = this.add.rectangle(700, 340, 40, 20, 0x4B5563).setDepth(-4)
    this.tweens.add({ targets: [scale, leftPan, rightPan], rotation: 0.04, duration: 2000, yoyo, repeat: -1, ease: 'Sine.easeInOut' })
  }

  createInGameMenu() {
    // 更明显的模式切换按钮
    const modeA = this.add.text(120, 70, '→ 黑洞纠错台', {
      fontSize: '18px', color: '#FFFFFF', backgroundColor: '#2563EB', padding: { x: 15, y: 8 }
    }).setOrigin(0.5).setInteractive({ useHandCursor: true })

    const modeB = this.add.text(300, 70, '→ 单位跃迁台', {
      fontSize: '18px', color: '#FFFFFF', backgroundColor: '#2563EB', padding: { x: 15, y: 8 }
    }).setOrigin(0.5).setInteractive({ useHandCursor: true })

    // 悬停效果
    modeA.on('pointerover', () => modeA.setStyle({ backgroundColor: '#1D4ED8' }))
    modeA.on('pointerout', () => modeA.setStyle({ backgroundColor: '#2563EB' }))
    modeB.on('pointerover', () => modeB.setStyle({ backgroundColor: '#1D4ED8' }))
    modeB.on('pointerout', () => modeB.setStyle({ backgroundColor: '#2563EB' }))

    modeA.on('pointerdown', () => {
      console.log('Switching to ModeAScene from ModeC')
      SoundUtils.playTransition()
      this.scene.switch('ModeAScene', { rangeMode: this.rangeMode, totalRounds: this.totalRounds })
    })
    modeB.on('pointerdown', () => {
      console.log('Switching to ModeBScene from ModeC')
      SoundUtils.playTransition()
      this.scene.switch('ModeBScene', { rangeMode: this.rangeMode, totalRounds: this.totalRounds })
    })
  }

  createNebulaBackground() {
    const key = 'nebula_c'
    if (this.textures.exists(key)) this.textures.remove(key)
    const tex = this.textures.createCanvas(key, 1280, 720)
    const ctx = tex.getContext()
    const grad = ctx.createRadialGradient(300, 200, 40, 300, 200, 500)
    grad.addColorStop(0, 'rgba(34,211,238,0.15)')
    grad.addColorStop(1, 'rgba(11,16,32,0.0)')
    ctx.fillStyle = grad
    ctx.fillRect(0,0,1280,720)
    tex.refresh()
    const bg = this.add.image(0,0,key).setOrigin(0)
    bg.setDepth(-10)
    this.tweens.add({ targets, x: 40, duration: 9000, yoyo, repeat: -1, ease: 'Sine.easeInOut' })
  }

  resetRounds() {
    this.currentRound = 0
    this.score = 0
    this.nextRound()
  }

  nextRound() {
    if (this.currentRound >= this.totalRounds) {
      SoundUtils.playRoundEnd()
      this.feedbackText.setText(`本轮结束！得分：${this.score}/${this.totalRounds}`)
      this.buttonA.setText('重新开始'); this.buttonB.setText('重新开始')
      this.buttonA.removeAllListeners(); this.buttonB.removeAllListeners()
      this.buttonA.setInteractive({ useHandCursor: true }).once('pointerdown', () => this.resetRounds())
      this.buttonB.setInteractive({ useHandCursor: true }).once('pointerdown', () => this.resetRounds())
      return
    }
    this.currentRound++
    this.generateNewQuestion()
    this.updateHud()
  }

  updateHud() {
    this.hudText.setText(`第 ${this.currentRound}/${this.totalRounds} 轮  |  得分 ${this.score}`)
  }

  generateNewQuestion() {
    // 使用新的比较数字生成方法
    const numbers = NumberUtils.generateComparisonNumbers(this.rangeMode)
    this.numberA = numbers.numberA
    this.numberB = numbers.numberB

    // 随机选择问题类型
    this.questionType = Math.random() < 0.5 ? 'bigger' : 'smaller'

    this.updateUI()
  }

  updateUI() {
    this.numberAText.setText(NumberUtils.formatNumber(this.numberA))
    this.numberBText.setText(NumberUtils.formatNumber(this.numberB))
    this.buttonA.setStyle({ backgroundColor: '#2D3748' })
    this.buttonB.setStyle({ backgroundColor: '#2D3748' })
    this.buttonA.setInteractive(); this.buttonB.setInteractive()

    // 根据问题类型更新提示文字
    const questionText = this.questionType === 'bigger' ? '哪个数字更大？' : '哪个数字更小？'
    const questionColor = this.questionType === 'bigger' ? '#22D3EE' : '#F59E0B'
    this.promptText.setText(questionText)
    this.promptText.setColor(questionColor)

    this.feedbackText.setText('')
    this.highlightLevels()
  }

  highlightLevels() {
    const levelA = NumberUtils.getHighestLevel(this.numberA)
    const levelB = NumberUtils.getHighestLevel(this.numberB)
    const levelInfoA = this.add.text(360, 320, levelA, { fontSize: '14px', color: '#9CA3AF' }).setOrigin(0.5)
    const levelInfoB = this.add.text(920, 320, levelB, { fontSize: '14px', color: '#9CA3AF' }).setOrigin(0.5)
    this.time.delayedCall(1500, () => {
      if (this.scene.isActive() && levelInfoA.active && levelInfoB.active) {
        levelInfoA.destroy();
        levelInfoB.destroy()
      }
    })
  }

  onChoiceSelected(choice: 'A' | 'B') {
    let isCorrect = false

    if (this.questionType === 'bigger') {
      // 问哪个更大
      isCorrect = (choice === 'A' && this.numberA > this.numberB) || (choice === 'B' && this.numberB > this.numberA)
    } else {
      // 问哪个更小
      isCorrect = (choice === 'A' && this.numberA < this.numberB) || (choice === 'B' && this.numberB < this.numberA)
    }

    if (choice === 'A') {
      this.buttonA.setStyle({ backgroundColor: isCorrect ? '#059669' : '#DC2626' })
      if (!isCorrect) this.buttonB.setStyle({ backgroundColor: '#059669' })
    } else {
      this.buttonB.setStyle({ backgroundColor: isCorrect ? '#059669' : '#DC2626' })
      if (!isCorrect) this.buttonA.setStyle({ backgroundColor: '#059669' })
    }
    this.buttonA.removeInteractive(); this.buttonB.removeInteractive()

    // 播放音效
    if (isCorrect) {
      SoundUtils.playCorrect()
      this.score++
      this.feedbackText.setText('正确！仔细比较数位值是关键')
      this.feedbackText.setColor('#10B981')
    } else {
      SoundUtils.playWrong()

      let correctNumber: number
      let correctLabel: string

      if (this.questionType === 'bigger') {
        if (this.numberA > this.numberB) {
          correctNumber = this.numberA
          correctLabel = 'A'
        } else {
          correctNumber = this.numberB
          correctLabel = 'B'
        }
      } else {
        if (this.numberA < this.numberB) {
          correctNumber = this.numberA
          correctLabel = 'A'
        } else {
          correctNumber = this.numberB
          correctLabel = 'B'
        }
      }

      const questionDesc = this.questionType === 'bigger' ? '更大' : '更小'
      const correctReading = NumberUtils.numberToChineseReading(correctNumber)

      this.feedbackText.setText(`错误！正确答案是${correctLabel}：${NumberUtils.formatNumber(correctNumber)}\n读作：${correctReading}\n比较技巧：逐位比较，注意数位的重要性`)
      this.feedbackText.setColor('#EF4444')
    }

    this.showComparisonEffect(isCorrect)
    this.time.delayedCall(1500, () => {
      if (this.scene.isActive()) {
        this.nextRound()
      }
    })
  }

  showComparisonEffect(isCorrect) {
    // 创建比较结果的视觉效果
    if (isCorrect) {
      // 正确答案：绿色光环效果
      const ring = this.add.circle(640, 360, 80, 0x10B981, 0)
      ring.setStrokeStyle(4, 0x10B981, 0.8)

      this.tweens.add({
        targets,
        scaleX: 1.5,
        scaleY: 1.5,
        alpha: 0,
        duration: 800,
        ease: 'Power2',
        onComplete: () => ring.destroy()
      })

      // 成功粒子效果
      for (let i = 0; i < 8; i++) {
        const angle = (i / 8) * Math.PI * 2
        const particle = this.add.circle(640, 360, 3, 0x22D3EE)

        this.tweens.add({
          targets,
          x: 640 + Math.cos(angle) * 120,
          y: 360 + Math.sin(angle) * 120,
          alpha: 0,
          duration: 600,
          ease: 'Power2',
          onComplete: () => particle.destroy()
        })
      }
    } else {
      // 错误答案：红色震动效果
      const originalX = this.numberAText.x
      const originalY = this.numberBText.x

      this.tweens.add({
        targets: [this.numberAText, this.numberBText],
        x: '+=10',
        duration: 50,
        yoyo,
        repeat: 3,
        ease: 'Power2',
        onComplete: () => {
          this.numberAText.x = originalX
          this.numberBText.x = originalY
        }
      })
    }
  }

  // 创建重置成绩按钮
  createResetButton() {
    const resetBtn = this.add.text(1200, 580, '🔄 重置成绩', {
      fontSize: '16px', color: '#FFFFFF', backgroundColor: '#DC2626',
      padding: { x: 12, y: 8 }
    }).setOrigin(0.5).setInteractive({ useHandCursor: true })

    // 悬停效果
    resetBtn.on('pointerover', () => {
      resetBtn.setStyle({ backgroundColor: '#B91C1C' })
    })
    resetBtn.on('pointerout', () => {
      resetBtn.setStyle({ backgroundColor: '#DC2626' })
    })

    // 点击事件
    resetBtn.on('pointerdown', () => {
      this.showResetConfirmation()
    })
  }

  // 显示重置确认对话框
  showResetConfirmation() {
    // 创建半透明背景
    const overlay = this.add.rectangle(640, 360, 1280, 720, 0x000000, 0.7)
    overlay.setInteractive()

    // 创建确认对话框
    const dialog = this.add.container(640, 360)
    const dialogBg = this.add.rectangle(0, 0, 400, 200, 0x1F2937)
    const dialogBorder = this.add.rectangle(0, 0, 400, 200).setStrokeStyle(2, 0x374151)

    const title = this.add.text(0, -60, '确认重置', { fontSize: '24px', color: '#FDE047' }).setOrigin(0.5)
    const message = this.add.text(0, -20, '确定要清除所有队伍的成绩吗？', { fontSize: '16px', color: '#D9E8FF' }).setOrigin(0.5)

    const confirmBtn = this.add.text(-80, 40, '确定', {
      fontSize: '18px', color: '#FFFFFF', backgroundColor: '#DC2626', padding: { x: 20, y: 10 }
    }).setOrigin(0.5).setInteractive({ useHandCursor: true })

    const cancelBtn = this.add.text(80, 40, '取消', {
      fontSize: '18px', color: '#FFFFFF', backgroundColor: '#6B7280', padding: { x: 20, y: 10 }
    }).setOrigin(0.5).setInteractive({ useHandCursor: true })

    dialog.add([dialogBg, dialogBorder, title, message, confirmBtn, cancelBtn])

    // 确定按钮事件
    confirmBtn.on('pointerdown', () => {
      this.groupBar.resetAll()
      overlay.destroy()
      dialog.destroy()
      console.log('星际对比跳成绩已重置')
    })

    // 取消按钮事件
    cancelBtn.on('pointerdown', () => {
      overlay.destroy()
      dialog.destroy()
    })

    // 点击背景关闭
    overlay.on('pointerdown', () => {
      overlay.destroy()
      dialog.destroy()
    })
  }

  destroy() {
    this.events.off('rangeChanged')
    super.destroy()
  }
}
